/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 62536
 * Date: 2024-03-25
 * Time: 23:20
 */
// 懒汉的方式实现单例模式.
class SingletonLazy {
    // 这个引用指向唯一实例. 这个引用先初始化为 null, 而不是立即创建实例
    private volatile static SingletonLazy instance = null;
    private static Object locker = new Object();

    public static SingletonLazy getInstance() {
        // 如果 Instance 为 null, 就说明是首次调用, 首次调用就需要考虑线程安全问题, 就要加锁.
        // 如果非 null, 就说明是后续的调用, 就不必加锁了.
        if (instance == null) {
            synchronized (locker) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }

    private SingletonLazy() { }
}

public class ThreadDemo2 {
    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();
        System.out.println(s1 == s2);
    }
}
